﻿//-----------------------------------------------------------------------
// <copyright file="WatermarkTextBoxFieldDefinition.cs" company="Jamie Knight">
// Copyright (c) Jamie Knight. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.ComponentModel.DataAnnotations;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using DevKnightlie.WPF.AutoForm.FieldDefinitions;
using Xceed.Wpf.Toolkit;

namespace DevKnightlie.WPF.AutoForm.WPFToolkit.FieldDefinitions
{
    /// <summary>
    /// Field definition which creates a WatermarkTextBox control
    /// </summary>
    public class WatermarkTextBoxFieldDefinition:BaseFieldDefinition
    {
        #region Properties

        /// <summary>
        /// Sets or returns the object to use for the watermark
        /// </summary>
        public object Watermark { get; set; }

        /// <summary>
        /// Sets or returns the name of a property to bind to the watermark
        /// </summary>
        public String WatermarkPropertyName { get; set; }

        #endregion

        #region Methods

        public override void BuildInputControl()
        {
            WatermarkTextBox textBox = new WatermarkTextBox()
            {
                HorizontalContentAlignment = HorizontalAlignment.Left,
                VerticalContentAlignment = VerticalAlignment.Center
            };
            Binding textBinding = new Binding(PropertyName);
            BindingOperations.SetBinding(textBox, TextBox.TextProperty, textBinding);
            SetupEnabledBinding(textBox);
            if (!String.IsNullOrWhiteSpace(WatermarkPropertyName))
            {
                Binding watermarkBinding = new Binding(WatermarkPropertyName);
                BindingOperations.SetBinding(textBox, WatermarkTextBox.WatermarkProperty, watermarkBinding);
            }
            else
            {
                textBox.Watermark = Watermark;
            }
            if (PropertyInfo != null)
            {
                // See if there's a MaxLength attribute against the property
                var attrs = (MaxLengthAttribute[])PropertyInfo.GetCustomAttributes(typeof(MaxLengthAttribute), false);
                if (attrs.Length > 0)
                {
                    MaxLengthAttribute attr = attrs[0];
                    textBox.MaxLength = attr.Length;
                }
            } 
            InputControl = ContainerControl = textBox;
        }

        #endregion
    }
}
